/**
 * Created by IntelliJ IDEA.
 * User: dinesh
 * Date: Apr 14, 2012
 * Time: 4:14:41 PM
 * To change this template use File | Settings | File Templates.
 */
/**
 * Created by IntelliJ IDEA.
 * User: dinesh
 * Date: Mar 31, 2012
 * Time: 8:29:44 PM
 * To change this template use File | Settings | File Templates.
 */
/***************************/

  //global vars
	var form = $("#frmData");
	var name1 = $("#fullName");
	var nameInfo = $("#nameInfo");
	var email = $("#email");
	var emailInfo = $("#emailInfo");
	var pass1 = $("#pass1");
	var pass1Info = $("#pass1Info");
	var pass2 = $("#pass2");
	var pass2Info = $("#pass2Info");
    var chpass1 = $("#chpass1");
    var chpass1Info = $("#chpass1Info");
    var chpass2 = $("#chpass2");
    var chpass2Info = $("#chpass2Info");
    var nic = $("#nic");
    var nicInfo = $("#nicInfo")
    var isEdit = false;

$(document).ready(function(){

	//var message = $("#message");

	//On blur
	name1.blur(validateName);
	email.blur(validateEmail);
	pass1.blur(validatePass1);
	pass2.blur(validatePass2);
     nic.blur(validateNic);
	//On key press
	name1.keyup(validateName);
	pass1.keyup(validatePass1);
	pass2.keyup(validatePass2);
    chpass1.keyup(validatePass3);
	chpass2.keyup(validatePass4);
	//message.keyup(validateMessage);
	//On Submitting
	form.submit(function(){
		if(validateName() & validateEmail() & validatePass1() & validatePass2() )
			return true
		else
			return false;
	});



    disableForm("frmData");
} );

//validation functions
	function validateEmail(){
		//testing regular expression
		var a = $("#email").val();
		var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
		//if it's valid email
		if(filter.test(a)){
			email.removeClass("errorField");
			emailInfo.text("");
			emailInfo.removeClass("errorField");
			return true;
		}
		//if it's NOT valid
		else{
			email.addClass("errorField");
			emailInfo.text("Type a valid e-mail please ");
			emailInfo.addClass("errorField");
			return false;
		}
	}
function validateNic(fn){
        var reg = /^[0-9]{9}[vVxX]$/;
        if (reg.test(nic.val())) {
            //test with db
            var params =encodeURIComponent("nic") + "="+nic.val()+"&" + encodeURIComponent("id") + "="+uid.val();
            ajaxPost("?employee/checkNic", params, function(data) {
			var response =JSON.parse(data);
			if (response.status==false) {
				return;
			}
             if(response.message){
                nic.removeClass("errorField");
		        nicInfo.text("");
			    nicInfo.removeClass("errorField");
                if (typeof fn === 'function') {
                    fn();
                }
			    return true;
             }else{
                nic.addClass("errorField");
			    nicInfo.text("NIC alredy exist !");
			    nicInfo.addClass("errorField");
			    return false;
             }
		});

        }else{
            nic.addClass("errorField");
			nicInfo.text("Please enter valid NIC number");
			nicInfo.addClass("errorField");
			return false;
        }
	}
	function validateName(){
		//if it's NOT valid
		if(name1.val().length < 4){
			name1.addClass("errorField");
			nameInfo.text("We want names with more than 3 letters!");
			nameInfo.addClass("errorField");
			return false;
		}
		//if it's valid
		else{
			name1.removeClass("errorField");
			nameInfo.text("");
			nameInfo.removeClass("errorField");
			return true;
		}
	}
	function validatePass1(){
		var a = $("#password1");
		var b = $("#password2");

		//it's NOT valid
		if(pass1.val().length <5 && isEdit==false){
			pass1.addClass("errorField");
			pass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'");
			pass1Info.addClass("errorField");
			return false;
		}
		//it's valid
		else{
			pass1.removeClass("errorField");
			pass1Info.text("");
			pass1Info.removeClass("errorField");
			validatePass2();
			return true;
		}
	}
	function validatePass2(){
		var a = $("#password1");
		var b = $("#password2");
		//are NOT valid
		if( pass1.val() != pass2.val()&& isEdit==false ){
			pass2.addClass("errorField");
			pass2Info.text("Passwords doesn't match!");
			pass2Info.addClass("errorField");
			return false;
		}
		//are valid
		else{
			pass2.removeClass("errorField");
			pass2Info.text("");
			pass2Info.removeClass("errorField");
			return true;
		}
	}
	function validatePass3(){
		var a = $("#password1");
		var b = $("#password2");

		//it's NOT valid
		if(chpass1.val().length <5 ){
			chpass1.addClass("errorField");
			chpass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'");
			chpass1Info.addClass("errorField");
			return false;
		}
		//it's valid
		else{
			chpass1.removeClass("errorField");
			chpass1Info.text("");
			chpass1Info.removeClass("errorField");
			validatePass4();
			return true;
		}
	}
	function validatePass4(){
		var a = $("#password1");
		var b = $("#password2");
		//are NOT valid
		if( chpass1.val() != chpass2.val() ){
			chpass2.addClass("errorField");
			chpass2Info.text("Passwords doesn't match!");
			chpass2Info.addClass("errorField");
			return false;
		}
		//are valid
		else{
			chpass2.removeClass("errorField");
			chpass2Info.text("");
			chpass2Info.removeClass("errorField");
			return true;
		}
	}
  function clearValidate(){
        email.removeClass("errorField");
		emailInfo.text("");
		emailInfo.removeClass("errorField");
        name1.removeClass("errorField");  //crooooooooooooooooooooooooooooom
        nameInfo.text("");
        nameInfo.removeClass("errorField");
        pass2.removeClass("errorField");
        pass2Info.text("");
        pass2Info.removeClass("errorField");
        pass1.removeClass("errorField");
        pass1Info.text("");
        pass1Info.removeClass("errorField");
  }

//////page data  ////
var isNew = false;

//////////// data Grid /////////
var mygrid;
var timeoutHnd;
var flAuto = false;
function gridGenerator() {
    mygrid = new dhtmlXGridObject('gridbox');
    mygrid.setImagePath("images/dhtmlx/imgs/");
    mygrid.setHeader("User Name,Name,NIC,Email,Profile Id,status");
    mygrid.setInitWidths("150,350,200,300,200,10");
    //mygrid.setInitWidths("150,150,100,100,100,100");
    mygrid.setColAlign("left,left,left,left,left,left");
    mygrid.setColSorting("server,server,server,na,na,na");
    mygrid.setColTypes("ro,ro,ro,ro,ro,ro");
    if (mygrid.setColspan){
       mygrid.attachEvent("onBeforeSorting", customColumnSort);
    }   
    mygrid.setSkin("dhx_skyblue");
    //mygrid.enablePaging(mode,pageSize,pagesInGrp,pagingControlsContainer,showRecInfo,pagingStateContainer);
    mygrid.enablePaging(true,10, 10, "pagingArea", true, "infoArea");
   // mygrid.setPagingSkin("bricks");
    mygrid.setPagingSkin("toolbar", "dhx_skyblue");
    //mygrid.setStyle("background-color:navy;color:white; font-weight:bold;", "","color:red;", "");
    mygrid.init();
    mygrid.attachEvent("onBeforePageChanged", function() {
        if (!this.getRowsNum()){
            return false;
        }
        return true;
    });
    mygrid.sortField_old = mygrid.sortField;
    mygrid.sortField = function() {
        mygrid.setColSorting("str,str,str,str,str,str");
        if (customColumnSort(arguments[0]))
        mygrid.sortField_old.apply(this, arguments);
    }
    mygrid.setColumnHidden(4,true);
    mygrid.setColumnHidden(5,true);
    mygrid.sortRows = function(col, type, order) {}
    mygrid.attachEvent("onRowSelect",doOnRowSelected);
    mygrid.attachEvent("onXLE", showLoading);
    mygrid.attachEvent("onXLS", function() {
        showLoading(true)
    });    
    mygrid.loadXML("?user/gridUser&un=" + Date.parse(new Date()),function(){
      var myToolbar=mygrid.aToolBar;
        //myToolbar.setSkin("dhx_black");
        
   });
}

function showLoading(fl) {
    var span = document.getElementById("recfound");
    if (!span)
        return;
    if (!mygrid._serialise) {
        span.innerHTML = "<i>Loading... available in Professional Edition of dhtmlxGrid</i>";
        return;
    }
    span.style.color = "red";
    if (fl === true)
    span.innerHTML = "loading...";
    else
    span.innerHTML = "";
}

function doSearch(ev) {
    if (!flAuto)
    return;
    var elem = ev.target || ev.srcElement;
    if (timeoutHnd)
    clearTimeout(timeoutHnd);
    timeoutHnd = setTimeout(reloadGrid, 500);
}
function reloadGrid() {
    var searchCriteriaUserName = document.getElementById("searchCriteria.username").value;
    var searchCriteriaName = document.getElementById("searchCriteria.name").value;
    var searchCriteriaNic = document.getElementById("searchCriteria.nic").value;
    showLoading(true);
    mygrid.clearAndLoad("?user/gridUser&userName=" + searchCriteriaUserName + "&name=" + searchCriteriaName + "&nic="+searchCriteriaNic+"&orderBy=" + window.s_col + "&direction=" + window.a_direction);
    if (window.a_direction)
    mygrid.setSortImgState(true, window.s_col, window.a_direction);
}
function enableAutosubmit(state) {
    flAuto = state;
    document.getElementById("submitButton").disabled = state;
}

function customColumnSort(ind) {
    if (ind == 1) {
        alert("Table can't be sorted by this column.");
        if (window.s_col)
        mygrid.setSortImgState(true, window.s_col, window.a_direction);
        return false;
    }
    var a_state = mygrid.getSortingState();
    window.s_col = ind;
    window.a_direction = ((a_state[1] == "des") ? "asc": "des");
   reloadGrid();
    return true;
}

function doOnRowSelected(rowID,celInd){
    clearForm("frmData");
    clearValidate();
    disableForm("frmData"); 
    document.getElementById("fullName").value  = mygrid.cells(rowID,1).getValue();
    document.getElementById("uname").value  = mygrid.cells(rowID,0).getValue();
    document.getElementById("email").value  = mygrid.cells(rowID,3).getValue();
    document.getElementById("nic").value  = mygrid.cells(rowID,2).getValue();      
    document.getElementById("id").value  = rowID;
    document.getElementById("uid").value  = rowID;
    document.getElementById("profile_id").value  = mygrid.cells(rowID,4).getValue();
    if(mygrid.cells(rowID,5).getValue()==1){
        document.getElementById("status").checked = true;
    }
    handleDefaultButtons("gridclick");
    enableElement("btnChangPass");
      $("#messagePanel").removeClass();
    $("#messagePanel").html("" ) ;
    isNew = false;

}

function initialize(fnAfterInit) {
    clearForm("frmData");
    clearValidate();
    disableForm("frmData");
    document.getElementById('uppass').style.display ="none";
    handleDefaultButtons("load");
    disableElement("btnChangPass");
}
function edit(){
    enableForm("frmData");
    document.getElementById('pass1').disabled=true;
    document.getElementById('pass2').disabled=true;
    document.getElementById('uppass').style.display ="none";
    handleDefaultButtons("edit");
    enableElement("btnChangPass");
    isEdit=true;
}
function add(){
    initialize();
    enableForm("frmData");
    isNew = true;
    // Reset  ID
    setField("id", "");
    setField("profile_id", "");
    document.getElementById('uppass').style.display ="none";
    handleDefaultButtons("add");
    $("#messagePanel").removeClass();
    $("#messagePanel").html("" ) ;
}
function changePassword(){
         document.getElementById('uppass').style.display ="block";
        disableElement("btnChangPass");
}
function resetPassword(){
    if(validatePass3() & validatePass4() ) {
        var params = serializeForm("frmDatapass") ;
        ajaxPost("?user/resetPassword", params, function(data) {

			var response =JSON.parse(data);

			if (response.status==false) {


				return;
			}

			// Success
			//actionResponse = response;
            $("#messagePanel").removeClass();
            $("#messagePanel").addClass(response.type);
            $("#messagePanel").html(response.message ) ;
            document.getElementById('uppass').style.display ="none";
           // reloadGrid();

			//initialize();

			// Save Success
            /*
			if (isAdd) {
				//showMessage("C", getMessage("save"));
				isAdd = false;
			}
			else {
				//showMessage("C", getMessage("update"));
			}
              */

		});
    }

		else
			return false;


}
function save(){
    validateNic(save2);

}

function save2(){
    if(validateName() & validateEmail() & validatePass1() & validatePass2() ) {
        var params = serializeForm("frmData") ;
        ajaxPost("?user/add", params, function(data) {

			var response =JSON.parse(data);

			if (response.status==false) {


				return;
			}

			// Success
			//actionResponse = response;
            $("#messagePanel").removeClass();
            $("#messagePanel").addClass(response.type);
            $("#messagePanel").html(response.message ) ;
            reloadGrid();

			initialize();

			// Save Success
            /*
			if (isAdd) {
				//showMessage("C", getMessage("save"));
				isAdd = false;
			}
			else {
				//showMessage("C", getMessage("update"));
			}
              */

		});
    }

		else
			return false;

    handleDefaultButtons("save");
}

function del(){
    var isDelete=confirm("Confirm to Delete '"+ document.getElementById("uname").value + "'  User !");

    if(isDelete ) {
        var params = serializeForm("frmData") ;
        ajaxPost("?user/delete", params, function(data) {
			var response =JSON.parse(data);
			if (response.status==false) {
				return;
			}
            $("#messagePanel").removeClass();
            $("#messagePanel").addClass(response.type);
            $("#messagePanel").html(response.message ) ;
            reloadGrid();
			initialize();
		});
    }
		else
			return false;
    handleDefaultButtons("delete");
}

function closePage(){
    window.location.href="?home";
}

function onLoad(){
     initialize();
     gridGenerator();
     enforcePrivileges();
}
//window.onload=doOnLoad;
onLoad();